package com.lipuwater.agent.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;

import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.adapter.BaseListAdapter;
import com.lipuwater.agent.app.base.ui.BaseListActivity;
import com.lipuwater.agent.app.base.utils.ListSettings;
import com.lipuwater.agent.app.config.AppConfig;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.api.ApiRequestsFile;
import com.lipuwater.agent.http.bean.city.CityInfoBean;
import com.lipuwater.agent.ui.adapter.ATCityChooseAdapter;
import com.lipuwater.agent.ui.utils.CityActivityList;
import com.lipuwater.agent.ui.utils.CityChooseUtils;
import com.lipuwater.agent.utils.ThreadUtils;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;
import com.ismartlib.utils.NetUtils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.realm.Realm;
import okhttp3.Call;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2016/12/15.
 * Email:924686754@qq.com
 * 地址选择
 */
public class CityChooseActivity extends BaseListActivity<Element> implements ATCityChooseAdapter.OnClick {
    private List<Element> mData = new ArrayList<>();
    //国家、省、市、区
    private String[] cityLevel = CityChooseUtils.getInstance().getCityLevel();
    private int currentLevel = CityChooseUtils.getInstance().getCurrentLevel();
    private ATCityChooseAdapter adapter;
    /**
     * 地区版本
     */
    private int mCityVersion;
    /**
     * 地区url
     */
    private String mCityUrl;

    private String filePath = AppConfig.APP_SDCARD_DIR + "city.xml";

    /**
     * 可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程
     */

    @Override
    protected void OnViewCreated() {
        viewToolbarShadow.setVisibility(View.VISIBLE);
        initTitle(R.drawable.icon_aleft, "选择收货地址");
        showLoading();
        CityActivityList.getInstance().addActivity(CityChooseActivity.this);

    }

    @Override
    public void requestData(boolean needRefresh) {
        if (CityActivityList.getInstance().getActivitySize() == 1) {
            getServiceRange();
        } else {
            Runnable syncRunnable = new Runnable() {
                @Override
                public void run() {
                    initData(filePath);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            };
            ThreadUtils.getInstance().getExecutorService().execute(syncRunnable);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (mData == null) {
                    showNoNetWork();
                    return;
                }
                onDataLoaded(mData);
                hideEmptyLayout();
            }
        }
    };

    private void getServiceRange() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        ApiRequestsBasis.getServiceRange(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    if (result.getParams() != null) {
                        mCityVersion = Integer.valueOf(result.getParams().get("version").toString());
                        mCityUrl = result.getParams().get("url").toString();
                        Realm realm = Realm.getDefaultInstance();
                        CityInfoBean cityInfoBeen = realm.where(CityInfoBean.class).findFirst();
                        if (cityInfoBeen == null) {
                            realm.beginTransaction();
                            CityInfoBean cityInfoBean = realm.createObject(CityInfoBean.class);
                            cityInfoBean.setVersion(mCityVersion);
                            cityInfoBean.setUrl(mCityUrl);
                            realm.commitTransaction();
                            //不存在，需要下载
                            loadFile(mCityUrl, true);
                        } else {
                            if (mCityVersion != cityInfoBeen.getVersion()) {
                                //版本过期,需要重新下载
                                loadFile(mCityUrl, true);
                            } else {
                                loadFile(mCityUrl, false);
                            }
                        }
                        realm.close();
                    }
                } else {
                    showNoNetWork();
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                showNoNetWork();
                if (!NetUtils.isConnected(CityChooseActivity.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    /**
     * @param url     下载文件的url
     * @param replace 是否替换文件，如果false的话直接替换
     *                true的话也下载替换掉
     */
    private void loadFile(final String url, final boolean replace) {
        Permission.getInstance(CityChooseActivity.this)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .results(new ResultCallBack() {
                    @Override
                    public void result(PermissionsResult result) {
                        Permission.getInstance(CityChooseActivity.this).unresults();
                        if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && result.isGranted()) {
                            File file = new File(filePath);
                            if (!file.exists()) {
                                //文件不存在
                                downloadFile(url);
                            } else if (file.exists() && replace) {
                                //文件存在，并且要替换
                                downloadFile(url);
                            } else {
                                //文件存在，不需要替换
                                Runnable syncRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        initData(filePath);
                                        Message msg = Message.obtain();
                                        msg.what = 1;
                                        handler.sendMessage(msg);
                                    }
                                };
                                ThreadUtils.getInstance().getExecutorService().execute(syncRunnable);
                            }
                        } else {
                            new AlertDialog.Builder(CityChooseActivity.this).
                                    setTitle("错误")
                                    .setMessage("请允许应用读取手机存储功能")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).show();
                        }
                    }
                });
    }


    private void downloadFile(String url) {
        ApiRequestsFile.downloadFile(this, url, AppConfig.APP_SDCARD_DIR, "city.xml", new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                Runnable syncRunnable = new Runnable() {
                    @Override
                    public void run() {
                        initData(filePath);
                        Message msg = Message.obtain();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                };
                ThreadUtils.getInstance().getExecutorService().execute(syncRunnable);
            }

            @Override
            public void onError(Call call, Exception e) {
                showNoNetWork();
                if (!NetUtils.isConnected(CityChooseActivity.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    @Override
    protected BaseListAdapter<Element> getListAdapter() {
        adapter = new ATCityChooseAdapter(this);
        adapter.setOnClick(this);
        return adapter;
    }

    @Override
    protected ListSettings getBaseSettings() {
        ListSettings settings = new ListSettings();
        settings.setLayoutType(ListSettings.LAYOUT_LIST);
        settings.setCanRefresh(false);
        settings.setCanLoadMore(false);
        return settings;
    }

    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    @Override
    public void ItemOnClick(View v, int position) {
        if (mNoDoubleClick.check()) return;
        currentLevel = CityChooseUtils.getInstance().getCurrentLevel();
        if (cityLevel == null) {
            CityActivityList.getInstance().exit();
            return;
        }
        if (currentLevel + 1 == cityLevel.length) {
            CityChooseUtils.getInstance().setChooseResults(mData.get(position).attributeValue("name"), mData.get(position).attributeValue("code"), true);
            CityActivityList.getInstance().exit();
            return;
        }
        currentLevel++;
        Iterator iter = mData.get(position).elementIterator(cityLevel[currentLevel]);
        if (iter.hasNext()) {
            CityChooseUtils.getInstance().setIter(iter);
            CityChooseUtils.getInstance().setCurrentLevel(currentLevel);
            Intent intent = new Intent(this, CityChooseActivity.class);
            startActivityForResult(intent, 1);
            CityChooseUtils.getInstance().setChooseResults(mData.get(position).attributeValue("name"), mData.get(position).attributeValue("code"), false);
        } else {
            CityChooseUtils.getInstance().setChooseResults(mData.get(position).attributeValue("name"), mData.get(position).attributeValue("code"), true);
            CityActivityList.getInstance().exit();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            currentLevel = CityChooseUtils.getInstance().getCurrentLevel();
            if (currentLevel == 0) {
                CityChooseUtils.getInstance().releaseRes();
            } else {
                CityChooseUtils.getInstance().setCurrentLevel(currentLevel--);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private List<Element> initData(String filePath) {
        Iterator iter = CityChooseUtils.getInstance().getIter();
        if (iter != null) {
            while (iter.hasNext()) {
                mData.add((Element) iter.next());
            }
            return mData;
        }
        try {
            FileInputStream inputStream = new FileInputStream(filePath);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            /*InputStream is = getAssets().open("area.xml");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();*/
            String xmlStr = new String(buffer, "UTF-8");

            //耗时操作,建立加入子线程再来个Loading
            Document doc = DocumentHelper.parseText(xmlStr);
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator countryregionIter = rootElt.elementIterator(cityLevel[currentLevel]);
            while (countryregionIter.hasNext()) {
                Element countryregionEle = (Element) countryregionIter.next();
                mData.add(countryregionEle);
            }
            return mData;
        } catch (IOException e) {
            mData = null;
            return null;
        } catch (DocumentException e) {
            mData = null;
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        currentLevel = CityChooseUtils.getInstance().getCurrentLevel();
        if (currentLevel == 0) {
            CityChooseUtils.getInstance().releaseRes();
        } else {
            CityChooseUtils.getInstance().setCurrentLevel(currentLevel - 1);
        }
        CityActivityList.getInstance().removeActivity(this);
    }


}